package admin

import (
	"github.com/gin-gonic/gin"
	"mojieshi/define"
	"mojieshi/models"
	"time"
)

type login struct {
	Bid      int    `json:"bid"`
	Phone    string `json:"phone" binding:"required"`                    //手机号
	Password string `gorm:"type:varchar(255); not null" json:"password"` //密码
}

// 登入
func Login(c *gin.Context) {
	//获取传值
	var jsonData login
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	//获取用户数据的
	var userData models.MAdminUser
	tx := models.DB.Model(new(models.MAdminUser)).Where("phone=? AND status=1", jsonData.Phone)
	if jsonData.Bid == 1 {
		tx = tx.Where("bid=?", 0)
	}
	tx = tx.First(&userData)
	if tx.Error != nil {
		define.Response.ResultFail(c, 10001, "您没有登入权限", "")
		return
	}
	//比对密码
	MD5PassWord := define.GetMD5(jsonData.Password)
	if MD5PassWord != userData.Password {
		define.Response.ResultFail(c, 10002, "密码错误", "")
		return
	}
	//生成token
	token, err := define.GenerateToken(userData.ID, userData.Phone)
	if err != nil {
		define.Response.ResultFail(c, 10003, "登入失败！", "")
		return
	}
	//存入token
	var data = map[string]interface{}{
		"token":    token,
		"login_at": time.Now().Unix(),
	}
	err = models.DB.Model(new(models.MAdminUser)).Where("id=?", userData.ID).Updates(&data).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, "登入失败", "")
		return
	}
	//写入登入日志
	models.LogAdd(1, "登入", userData.ID, "管理员登入", userData.Bid, userData.Aid)
	define.Response.ResultSuccess(c, "登入成功!", map[string]interface{}{
		"token":   token,
		"user_id": userData.ID,
	})
}
